//
//  RemoveVC.m
//  XQContact
//
//  Created by ladystyle100 on 2017/8/29.
//  Copyright © 2017年 SyKingW. All rights reserved.
//

#import "RemoveVC.h"
#import "XQABManager.h"

static NSString *reusing_ = @"RemoveVCCell";

@interface RemoveVC () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <XQABModel *> *dataArr;

@end

@implementation RemoveVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self.view addSubview:self.tableView];
}

- (void)initData {
    __weak typeof(self) weakSelf = self;
    [[XQABManager manager] getAllContactWithCompletion:^(NSArray<XQABModel *> *modelArr) {
        weakSelf.dataArr = [modelArr mutableCopy];
        [weakSelf.tableView reloadData];
    }];
}

#pragma mark -- UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusing_ forIndexPath:indexPath];
    
    XQABModel *model = self.dataArr[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"id %d, name %@%@", model.contactID, model.lastName, model.firstName];
    
    return cell;
}

#pragma mark -- UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BOOL is = [[XQABManager manager] removeContactWithContactID:self.dataArr[indexPath.row].contactID];
    if (!is) {
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [SVProgressHUD showSuccessWithStatus:@"删除失败"];
        return;
    }
    
    [SVProgressHUD showSuccessWithStatus:@"删除成功"];
    
    [self.dataArr removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}

#pragma mark -- get

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:reusing_];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        
    }
    return _tableView;
}


@end
















